package com.gc.common.shiro.services;

import com.gc.common.util.MyUtil;
import com.gc.dao.custom.*;
import com.gc.pojo.SysRole;
import com.gc.pojo.SysUser;
import com.gc.pojo.SysUserAssociation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author xyl
 * @create 2020/8/7 17:10
 * @desc 用于权限service
**/
@Service
public class SysLoginService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuTwoMapper menuTwoMapper;
    @Autowired
    private AuthMapper authMapper;
    @Autowired
    private UserAssociationMapper userAssociationMapper;
    @Autowired
    private MyUtil myUtil;


    public SysUser login(String loginName, String password) {
        SysUser user =  userMapper.selectByLoginName(loginName);
        return user;
    }

    /**
     * 获取用户角色
     * @param uid 用户id
     * @return
     */
    public Set<String> getUserRoleKeyByUid(Integer uid) {
//        String roles =  userAssociationMapper.selectRolesByUId(uid);
//        if(StringUtils.isEmpty(roles)) return null;
//        SysRole sysRole = roleMapper.selectByPrimaryKey(Integer.valueOf(roles));
//        if(null == sysRole)  return null;
//        Set<String> set = new HashSet<>();
//        set.add(sysRole.getRoleKey());
        SysRole role = roleMapper.selectByUserId(uid);
        Set<String> set = new HashSet<>();
        set.add(role.getRoleKey());
        return set;
    }

    /**
     * 获取用户权限
     * @param uid 用户id
     * @return
     */
    public Set<String> getUserAuthsByUid(Integer uid) {
        Set<String> all = new HashSet<>();
        Set<String> perms1 = null;
        Set<String> perms2 = null;
        //先查询关联表数据
        SysUserAssociation association = userAssociationMapper.selectByUid(uid);
        if(null == association) return null;
        //拆分数据
        List<Integer> menus = myUtil.split(association.getMenusTwo());
        List<Integer> auths = myUtil.split(association.getAuths());
        if(menus != null){
            //查询菜单权限
            perms1 = menuTwoMapper.selectPermsByMIdToSet(menus);
        }
        if(auths != null){
            //查询操作权限
            perms2 = authMapper.selectAuthsByAIdToSet(auths);
        }
        //合并
        if(perms1 != null){
            all.addAll(perms1);
        }
        if(perms2 != null){
            all.addAll(perms2);
        }
        return all;
    }
}
